"use client"

import { useState, useEffect } from "react"
import { useLocation, useNavigate } from "react-router-dom"
import "./HomePage.css"

const HomePage = () => {
  const getAuthHeaders = () => {
    const token = localStorage.getItem("token")
    return {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": "application/json",
    }
  }

  // 特色视频数据（宣传栏）
  const [hotVideos, setHotVideos] = useState([])
  // 推荐种子数据
  const [recommendedTorrents, setRecommendedTorrents] = useState([])
  // 全部视频数据
  const [allVideos, setAllVideos] = useState([])
  // 添加新的类型数据状态
  const [foodTorrents, setFoodTorrents] = useState([])
  const [loveTorrents, setLoveTorrents] = useState([])
  const [sportsTorrents, setSportsTorrents] = useState([])
  const [techTorrents, setTechTorrents] = useState([])

  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [leaderboardData, setLeaderboardData] = useState([])

  // Tab状态
  const [activeTab, setActiveTab] = useState("all")
  const [allVideosLoading, setAllVideosLoading] = useState(false)
  const [recommendedLoading, setRecommendedLoading] = useState(false)
  // 添加新的loading状态
  const [foodLoading, setFoodLoading] = useState(false)
  const [loveLoading, setLoveLoading] = useState(false)
  const [sportsLoading, setSportsLoading] = useState(false)
  const [techLoading, setTechLoading] = useState(false)

  const default_coverImage = "data:image/svg+xml;charset=UTF-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='300' viewBox='0 0 200 300'%3E%3Crect width='200' height='300' fill='%23e0e0e0'/%3E%3Ctext x='50%25' y='50%25' fill='%23666' font-family='Arial, sans-serif' font-size='16' text-anchor='middle' dominant-baseline='middle'%3ENo Cover Image%3C/text%3E%3C/svg%3E"

  // 获取热门视频
  const fetchHotVideos = async () => {
    try {
      const response = await fetch(`/user/recommendHotTorrent?user_id=${localStorage.getItem("userId")}`, {
        method: "POST",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("网络错误，请稍后再试。")
      }

      const data = await response.json()
      if (data.code !== 0 || !data.result) {
        throw new Error(data.msg || "返回失败")
      } else {
        setHotVideos(data.rows)
      }
    } catch (error) {
      console.error("Error fetching hot videos:", error)
    }
  }

  // 获取用户积分
  const fetchLeaderboardData = async () => {
    try {
      const response = await fetch(`/user/leaderboard`, {
        headers: getAuthHeaders(),
      })
      if (!response.ok) {
        throw new Error("网络错误，请稍后再试。")
      }
      const data = await response.json()
      setLeaderboardData(data.rows)
    } catch (error) {
      console.error("Error fetching leaderboard data:", error)
    }
  }

  // 获取全部视频
  const fetchAllVideos = async () => {
    setAllVideosLoading(true)
    setError(null) // 重置错误状态
    try {
      const response = await fetch(`/torrent/findAllTorrentList`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("网络错误，请稍后再试。")
      }

      const data = await response.json()
      setAllVideos(data)
    } catch (error) {
      console.error("Error fetching all videos:", error)
      setError(error.message)
    } finally {
      setAllVideosLoading(false)
    }
  }

  // 获取推荐种子
  const fetchRecommendedTorrents = async () => {
    setRecommendedLoading(true)
    setError(null) // 重置错误状态
    try {
      const response = await fetch(`/user/recommendSimilarUsers?user_id=${localStorage.getItem("userId")}`, {
        method: "POST",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("网络错误，请稍后再试。")
      }

      const data = await response.json()
      if (data.code !== 0 || !data.result) {
        throw new Error(data.msg || "返回失败")
      }

      setRecommendedTorrents(data.rows)
    } catch (error) {
      console.error("Error fetching recommended torrents:", error)
      setError(error.message)
    } finally {
      setRecommendedLoading(false)
    }
  }

  // 获取不同类型的种子数据
  const fetchTypeTorrents = async (type) => {
    const setLoadingMap = {
      food: setFoodLoading,
      love: setLoveLoading,
      sports: setSportsLoading,
      tech: setTechLoading,
    }

    const setDataMap = {
      food: setFoodTorrents,
      love: setLoveTorrents,
      sports: setSportsTorrents,
      tech: setTechTorrents,
    }

    // 类型到标签的映射
    const typeToTagMap = {
      food: "美食",
      love: "爱情",
      sports: "运动",
      tech: "科技",
    }

    const setLoadingFunc = setLoadingMap[type]
    const setDataFunc = setDataMap[type]
    const tag = typeToTagMap[type]

    setLoadingFunc(true)
    setError(null)

    try {
      const response = await fetch(`/torrent/searchByTag?tag=${encodeURIComponent(tag)}`, {
        method: "GET",
        headers: getAuthHeaders(),
      })

      if (!response.ok) {
        throw new Error("网络错误，请稍后再试。")
      }

      const data = await response.json()
      setDataFunc(data)
    } catch (error) {
      console.error(`Error fetching ${type} torrents:`, error)
      setError(error.message)
    } finally {
      setLoadingFunc(false)
    }
  }

  useEffect(() => {
    fetchLeaderboardData()
    fetchHotVideos()
    // 默认加载全部视频
    fetchAllVideos()
    setLoading(false)
  }, [])

  // 处理tab切换
  const handleTabChange = (tabName) => {
    setActiveTab(tabName)
    console.log("切换到标签:", tabName)

    switch (tabName) {
      case "recommended":
        fetchRecommendedTorrents()
        break
      case "all":
        fetchAllVideos()
        break
      case "food":
        fetchTypeTorrents("food")
        break
      case "love":
        fetchTypeTorrents("love")
        break
      case "sports":
        fetchTypeTorrents("sports")
        break
      case "tech":
        fetchTypeTorrents("tech")
        break
      default:
        break
    }
  }

  // 处理跳转到下载页面
  const navigate = useNavigate()
  const location = useLocation()
  const handleDownloadClick = (torrentId) => {
      const token = localStorage.getItem('token');
      const userId = localStorage.getItem('userId');

      if (!token || !userId) {
          navigate('/login', { state: { from: location.pathname } });
          return;
      }

      navigate(`/download?torrent_id=${torrentId}`);
  };

  // 状态管理
  const [currentIndex, setCurrentIndex] = useState(0) // 特色视频索引

  // 特色视频自动轮播
  useEffect(() => {
    if (hotVideos.length === 0) return

    const interval = setInterval(() => {
      setCurrentIndex((prevIndex) => (prevIndex + 1) % hotVideos.length)
    }, 5000)

    return () => clearInterval(interval)
  }, [hotVideos.length])

  // 处理点导航点击
  const handleDotClick = (index) => {
    setCurrentIndex(index)
  }

  // 当前特色视频数据
  const currentVideo = hotVideos[currentIndex] || {
    title: "加载中...",
    description: "请稍等...",
    coverImage: "https://via.placeholder.svg/800x400",
  }

  // 渲染视频卡片
  const renderVideoCard = (torrent) => (
    <div key={torrent.torrentId} className="video-card"
      onClick={() => handleDownloadClick(torrent.torrentId)}
      style={{ cursor: "pointer" }} 
    >
      <div className="video-thumbnail">
        <img
          src={torrent.coverImage ? `data:image/jpeg;base64,${torrent.coverImage}` : default_coverImage}
          alt={torrent.title}
        />
      </div>
      <div className="video-details">
        <h3 className="video-name">{torrent.title}</h3>
        <div className="video-meta">
          <div className="creator-info">
            {torrent.tags && <span className="video-tag">{torrent.tags}</span>}
            <span className="upload-time">{new Date(torrent.uploadTime).toLocaleDateString()}</span>
            <span className="upload-time">{formatSize(torrent.sizeGB)}</span>
          </div>
        </div>
      </div>
    </div>
  )

  // 渲染视频网格内容
  const renderVideoGrid = () => {
    const renderGrid = (data, loading, emptyMessage) => (
      <div className="video-grid">
        {loading && <div className="loading">加载中...</div>}
        {error && !loading && <div className="error">错误: {error}</div>}
        {!loading && !error && data.length === 0 && <div className="empty">{emptyMessage}</div>}
        {!loading && !error && data.map(renderVideoCard)}
      </div>
    )

    switch (activeTab) {
      case "all":
        return renderGrid(allVideos, allVideosLoading, "暂无视频")
      case "recommended":
        return renderGrid(recommendedTorrents, recommendedLoading, "暂无推荐种子")
      case "food":
        return renderGrid(foodTorrents, foodLoading, "暂无美食")
      case "love":
        return renderGrid(loveTorrents, loveLoading, "暂无爱情")
      case "sports":
        return renderGrid(sportsTorrents, sportsLoading, "暂无运动")
      case "tech":
        return renderGrid(techTorrents, techLoading, "暂无科技")
      default:
        return renderGrid(allVideos, allVideosLoading, "暂无视频")
    }
  }

  // 自动调整sizeGB
  const formatSize = (sizeInGB) => {
    const sizeInMB = sizeInGB * 1024
    const sizeInKB = sizeInMB * 1024

    if (sizeInGB >= 1) {
      // 大于等于1GB，显示GB并保留2位小数
      return `${sizeInGB.toFixed(2)} GB`
    } else if (sizeInMB >= 1) {
      // 大于等于1MB但小于1GB，显示MB并保留2位小数
      return `${sizeInMB.toFixed(2)} MB`
    } else {
      // 小于1MB，显示KB并取整数
      return `${sizeInKB.toFixed(2)} KB`
    }
  }

  return (
    <div className="homepage">
      {/* Floating Leaderboard */}
      <div className="leaderboard-container">
        <div className="leaderboard">
          <div className="leaderboard-header">
            <h3>做种排行榜</h3>
            <div className="leaderboard-tabs">
              <span>排名</span>
              <span>名称</span>
              <span>积分</span>
            </div>
          </div>
          <div className="leaderboard-content">
            {leaderboardData
              .filter((user) => user != null)
              .map((user, index) => (
                <div key={user.id} className="leaderboard-item">
                  <div className="rank">
                    {index < 3 ? (
                      <span className={`top-rank rank-${index + 1}`}>{index + 1}</span>
                    ) : (
                      <span className="normal-rank">{index + 1}</span>
                    )}
                  </div>
                  <div className="user-info">
                    <span className="rank-user-name">{user.nickname}</span>
                  </div>
                  <div className="points">{user.userPoints.toLocaleString()}</div>
                </div>
              ))}
          </div>
        </div>
      </div>

      {/* Featured Video Banner */}
        <section className="featured-video">
          <img className="video-cover-image"
            src={currentVideo.coverImage ? `data:image/jpeg;base64,${currentVideo.coverImage}` : default_coverImage}
            alt={currentVideo.title}
            onClick={() => handleDownloadClick(currentVideo.torrentId)}
            style={{ cursor: "pointer" }}
          />
          <div className="video-info">
            <h2 className="video-title">{currentVideo.title}</h2>
            <p className="video-description">{currentVideo.description}</p>
          </div>

          {/* Dot Navigation */}
          <div className="dot-navigation">
            {hotVideos.map((_, index) => (
              <span
                key={index}
                className={`dot ${currentIndex === index ? "active" : ""}`}
                onClick={() => handleDotClick(index)}
              ></span>
            ))}
          </div>

          {/* Arrow Navigation */}
          <div className="arrow-navigation">
            <button
              className="arrow arrow-left"
              onClick={() => setCurrentIndex((prevIndex) => (prevIndex === 0 ? hotVideos.length - 1 : prevIndex - 1))}
            >
              &lt;
            </button>
            <button
              className="arrow arrow-right"
              onClick={() => setCurrentIndex((prevIndex) => (prevIndex + 1) % hotVideos.length)}
            >
              &gt;
            </button>
          </div>
      </section>

      {/* Video Section with Custom Tabs */}
      <section className="video-section">
        <div className="custom-tabs">
          <div className="tab-list">
            <button
              className={`home-tab-button ${activeTab === "all" ? "active" : ""}`}
              onClick={() => handleTabChange("all")}
            >
              全部
            </button>
            <button
              className={`home-tab-button ${activeTab === "recommended" ? "active" : ""}`}
              onClick={() => handleTabChange("recommended")}
            >
              推荐
            </button>
            <button
              className={`home-tab-button ${activeTab === "food" ? "active" : ""}`}
              onClick={() => handleTabChange("food")}
            >
              美食
            </button>
            <button
              className={`home-tab-button ${activeTab === "love" ? "active" : ""}`}
              onClick={() => handleTabChange("love")}
            >
              爱情
            </button>
            <button
              className={`home-tab-button ${activeTab === "sports" ? "active" : ""}`}
              onClick={() => handleTabChange("sports")}
            >
              运动
            </button>
            <button
              className={`home-tab-button ${activeTab === "tech" ? "active" : ""}`}
              onClick={() => handleTabChange("tech")}
            >
              科技
            </button>
          </div>

          <div className="tab-content">{renderVideoGrid()}</div>
        </div>
      </section>
    </div>
  )
}

export default HomePage
